var app = getApp();
const utils = require('../../utils/util.js');
const wxpay = require('../../utils/pay.js');
Page({
  data: {
    lists:{UserId: 0, AccountBalance: 0, OrdersTotal: 0,RequestBalance: 0},
    platform: '',
    showModel: false, //是否显示充值弹框
    inputMoney: 0,
    cardCount: 0,   //我的用户数
    agentState: 0, //是否是代理商: 1 代理商, 2 分销商
    myCardId: -1,  //我的名片id, 0 未创建, >0 已创建
    qrCode: ''    //分享二维码
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    this.setData({
      platform: app.globalData.platform
    })
    utils.authLogin(()=>{
      that.getMyStaff();
    })
  },

  onShow: function () {
  },
  
  //获取分销商信息，如果分销商不存在，则创建新的
  GetDistributorInfo: function () {
    var that = this;
    var disId = wx.getStorageSync('disid')
    var agentId = wx.getStorageSync('agentid')
    if (disId == "" || disId == null){
        disId = 0
    }
    if (agentId == "" || agentId == null) {
        agentId = 0
    }
    wx.request({
      url: app.globalData.host + '/api/Distributor/GetDistributorAndCreate',
      data: {
        userId: app.globalData.myUserInfo.Uid,  //当前会员ID(非店长、非分店)
        disId: disId,
        agentId: agentId,
        storeId: app.globalData.storeId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          let list = res.data.Data;
          list.accumulated = (parseFloat(list.AccountBalance) + parseFloat(list.RequestBalance)).toFixed(2)//累计收益 = 账户余额 + 已提现金额
          that.setData({
            lists: list,
            agentState: list.IsAgent == 1 ? 1 : 2
          })
        } else {
          utils.showModal(res.data.Message); 
        }
      }
    })
  },

  //我的名片
  getMyStaff: function(){
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/staff/GetStaffIdByUid?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          let myCardId = 0;
          if(res.data.Data){
            myCardId = res.data.Data.Id;
            that.getCardItemTotal();
            that.GetDistributorInfo();          
          }
          that.setData({
            myCardId: myCardId
          })
        }
      }
    })
  },

  //我的用户数
  getCardItemTotal: function() {
    let that = this;
    let jjCard = app.globalData.jjCard;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardItemTotal?cardItemId=' + jjCard.Id + '&cardType=' + jjCard.CardType + '&saleUid=' + app.globalData.myUserInfo.Uid,
      success: function(res) {
        if (res.data.Code == 0) {        
          that.setData({
            cardCount: res.data.Data.CardCount
          })
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },
  //苹果升级申请申请余额代充
  requestAccountBalance: function () {
    wx.showModal({
      title: '提示',
      content: '发送升级申请，保障账户安全！\r\n专属运营经理会在24小时内联系您',
      confirmText: "立即申请",
      success(res) {
        if (res.confirm) {
          wx.showLoading({title: '申请中',mask: true})
          wx.request({
            url: app.globalData.host + '/api/Distributor/RequestAccountBalance?uid=' + app.globalData.userInfo.Uid,
            success: function (res) {
              wx.hideLoading();
              if (res.data.Code == 0) {
                utils.showToast('申请成功');
              } else {
                utils.showModal(res.data.Message);              
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  
  //安卓手机现金直冲
  submitAccountBalanceOrder: function () {
    if (!this.checkMoney(this.data.inputMoney)){
      utils.showToast('请输入50-9900整数'); 
      return;
    }
    wx.showLoading({title: '充值中',mask: true})
    wx.request({
      url: app.globalData.host + '/api/Order/SubmitAccountBalanceOrder',
      data: {
        uid: app.globalData.userInfo.Uid,
        count: this.data.inputMoney/50
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          wxpay.wxpay(app, res.data.Data, 1)
        } else {
          utils.showModal(res.data.Message);         
        }
      }
    })
  },

  // 帮好友充值
  toRechargeOthers: function(){
    wx.navigateTo({
      url: '/fenxiao/rechargeOther/index',
    })
  },

  //开通免费推广版
  createStaffOrder: function(){
    let industryCode = 1; //免费推广版
    let jump = 2;
    let relaunchUrl = '/fenxiao/home/index';
    this.getShareStaffId((cardId)=>{
      wxpay.createStaffOrder(app, cardId, industryCode, jump, 3, relaunchUrl);
    })    
  },
  
  //获取推荐人
  getShareStaffId: function(callback){
    let cardId = wx.getStorageSync("cardId");
    if(cardId){
      callback(cardId);
      return;
    }
    //用默认名片当推荐人
    wx.request({
      url: app.globalData.host + '/api/BusinessCard/GetStoreDefaultStaff?addClient=0&uid=' + app.globalData.userInfo.Uid,
      success: function (res) {       
        if (res.data.Code == 0) {
          callback(res.data.Data.Id);
        } else {
          utils.showModal(res.data.Message);         
        }
      }
    })
  },
  //生成分享二维码
  getWxaCodeFile(callback) {
    var that = this;
    if(that.data.qrCode){
      callback(that.data.qrCode);
      return;
    }
    let source = 1;
    let path = 'pages/indexDefault/index?t=1&p=' + that.data.myCardId  + '#' +  app.globalData.myUserInfo.Uid + '#'  + source;
    wx.request({
      url: app.globalData.host + '/api/Store/GetWxaCodeFile',
      data:{
        storeId: app.globalData.storeId,
        path: path,
        storeAppId: app.globalData.storeAppId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          callback(res.data.Data);          
        }       
      }
    })
  },
  //充值弹框
  showModel: function () {
    this.setData({ showModel: !this.data.showModel })
  },

  toTixian:function(){//提现
    wx.navigateTo({
      url: '/fenxiao/tixian/index?money=' + this.data.lists.AccountBalance,
    })
  },
  //分享二维码
  toPoster: function(){
    this.getWxaCodeFile((qrCode)=>{
      wx.navigateTo({
        url: '/fenxiao/shareCodes/index?template=platform&qrCode=' + qrCode + '',
      })
    })
  },
  //代理申请
  toAgentApply:function(){
    this.toH5Page(app.globalData.webhost + 'disRegionApply.html');
  },
  //标签用户列表
  toTabUsers: function(e){
    let url =app.globalData.webhost + 'newLabel.html?Id=1143&total=' + this.data.cardCount;
    this.toH5Page(url);
  },  
  //推荐规则
  toMeituanRule: function(){
    this.toH5Page(app.globalData.webhost + 'meituanRule.html');
  },
  toH5Page: function(url){
    if(! wx.getStorageSync("cardId")){
      wx.setStorageSync('cardId', this.data.myCardId);
    }
    wx.navigateTo({
      url: '/pages/h5page/index?url=' +  encodeURIComponent(url)
    })
  },
  bindInputValue: function (e) {
    let inputMoney = e.detail.value ? parseFloat(e.detail.value) : 0;
    this.setData({
      inputMoney: inputMoney
    })
  },  
  //金额验证
  checkMoney: function (obj){
    if(!obj){
      return false;
    }else{
      return typeof obj === 'number' && obj % 50 === 0;//是整数，则返回true，否则返回false
    }
  },
  checkInput: function(){ 
  },
  //拨打电话
  callPhone: function(e){
    let mobile = e.currentTarget.dataset.mobile;
    if (mobile) {
      wx.makePhoneCall({
        phoneNumber: mobile
      })
    }
  }
})